package com.example.tool.task;

import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

public class JavaPdfHelloWorld {

    /**
     * 根据PDF模板生成PDF文件
     * @param sourceFile 原模板文件
     * @param fileName 动态输入写入的文件
     * @param fieldMap 动态数据值
     * @param absolutePath
     */
    public static void toPDFWriteValue(String sourceFile, String fileName, String targetFilePath, Map<String, Object> fieldMap, String absolutePath)throws Exception{
            PdfReader reader = new PdfReader(sourceFile);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            PdfStamper ps = new PdfStamper(reader, bos);
            AcroFields s = ps.getAcroFields();
            //解决中文
            com.itextpdf.text.pdf.BaseFont bfChinese = com.itextpdf.text.pdf.BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
            s.addSubstitutionFont(bfChinese);
            //判断写入文件是否存在，不存在创建
            File file = new File(targetFilePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            String fileSavePath = targetFilePath + fileName;
            File file1 = new File(fileSavePath);
            if (!file1.exists()) {
                file1.createNewFile();
            }

            //将条形码照片写入pdf
            Rectangle signRect  = s.getFieldPositions("image").get(0).position;
            Image image  = Image.getInstance(absolutePath);
            PdfContentByte overContent = ps.getOverContent(s.getFieldPositions("image").get(0).page);
            float x = signRect.getLeft();//获取坐标
            float y = signRect.getBottom();//获取坐标
            image.scaleToFit(signRect.getWidth(), signRect.getHeight());
            image.setAbsolutePosition(x, y);// The image must have absolute positioning.
            overContent.addImage(image);


            for(String key:fieldMap.keySet()){
                s.setField(key,fieldMap.get(key).toString());
            }
            ps.setFormFlattening(true);
            ps.close();
            FileOutputStream fos = new FileOutputStream(fileSavePath);
            fos.write(bos.toByteArray());
            fos.close();
    }






    public static void main(String[] args) throws Exception {
        /**
         * 基本配置信息
         */


        String barcode="J2350006090100";
        String path = "D:/Desktop/kpsw/upload/pdfsource/bar.png";//生成条形码照片的位置
        String sourceFile="D:/Desktop/kpsw/upload/pdfsource/javaTest.pdf";
        String fileName="new.pdf";
        String targetFilePath="D:/Desktop/kpsw/upload/newpdfsource/";
        Map<String,Object> fieldMap=new HashMap<>();
        fieldMap.put("sampleNumber","脱落细胞");
        fieldMap.put("customerId",barcode);
        fieldMap.put("patientName",barcode);
        fieldMap.put("medicalRecordNo",barcode);
        fieldMap.put("dtep",barcode);
        fieldMap.put("patientGender","女");
        fieldMap.put("Barcode","TCT00010");
        fieldMap.put("inputDate","2021-11-25 00:00:00");
        fieldMap.put("inspectItem",barcode);
        fieldMap.put("clinicalDiagnosis",barcode);
        fieldMap.put("MgResult",barcode);
        fieldMap.put("NGResult",barcode);
        fieldMap.put("referenceRange",barcode);


        long  startTime = System.currentTimeMillis();    //获取开始时间

        //先获取条形码生成的照片
        File imageFile = BarcodeUtil.generateFile(barcode, path);
        long endTime = System.currentTimeMillis();    //获取结束时间
        System.out.println("程序运行条形码生成时间：" + (endTime - startTime) + "ms");    //输出程序运行时间



        startTime = System.currentTimeMillis();    //获取开始时间
        //对pdf写入条形码图片，然后再添加数据


        toPDFWriteValue(sourceFile,fileName,targetFilePath,fieldMap,imageFile.getAbsolutePath());
        endTime = System.currentTimeMillis();    //获取结束时间
        System.out.println("程序运行修改pdf时间：" + (endTime - startTime) + "ms");    //输出程序运行时间

    }
}
